package com.hnust.root.service.file;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.hnust.root.common.constant.GlobalConstant;
import com.hnust.root.common.util.OSSUtil;
import com.hnust.root.web.config.GlobalConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author zhusir
 * @Date 2019/2/1
 * @Desc
 */
@Service
public class OSSServicesImpl implements IOSSService {

    private final Log LOGGER = LogFactory.get();

    @Value("${oss.accessKeyId}")
    private  String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private  String accessKeySecret;

    @Value("${oss.default.dir}")
    private String DIR;

    @Autowired
    private OSSUtil ossUtil;

    /**
     * OSS上传文件
     *
     * @param file       本地文件
     * @param catalogue  目录名
     * @return 文件存储路径
     * @throws IOException
     */
    @Override
    public String upload(MultipartFile file, String catalogue) {
        CompletableFuture<Boolean> result;
        boolean isSuccess = false;
        LocalDate now = LocalDate.now();
        String filename;
        String baseDir = String.valueOf(now.getYear()) + "/" + now.getMonthValue() + "/" + now.getDayOfMonth() + "/" + RandomUtil.randomInt(1, 100000) + "-" + file.getOriginalFilename();
        if (catalogue == null || catalogue.trim().length() != 0) {
            filename = DIR + "/" + baseDir;
        } else {
            filename = DIR + "/" + catalogue + "/" + baseDir;
        }


        try {
            result = ossUtil.putObjectAsyn(filename, file);
            isSuccess = result.get();
        } catch (IOException | InterruptedException | ExecutionException e) {
            LOGGER.error("文件上传失败，error msg : {}", e.getMessage());
            e.printStackTrace();
        }
        return isSuccess ? GlobalConfig.getOssDomain() + filename : null;
    }

    /**
     * 通过文件名下载文件
     *
     * @param fileUrl       文件在OSS上存放的路径
     * @param localFileName 本地要创建的文件名
     */
    public boolean downloadFile(String fileUrl, String localFileName) throws OSSException{
        boolean result = false;
        try {
            result = ossUtil.getObject(fileUrl, localFileName).get();
        } catch (Exception e) {
            LOGGER.error("文件下载出错 error msg: {}", e.getMessage());
        }
        return result;
    }
}
